import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    my_goods_number:0,
    products:[
      {name:'衣服',price:200},
      {name:'裤子',price:100},
      {name:'帽子',price:50},
      {name:'鞋子',price:300},
      {name:'睡衣',price:150},
    ],
    my_goods:[],
    need:0

  },
  mutations: {
    add_good(state,product) {
      var flag = true;
      for(var i = 0;i< state.my_goods_number;i++){
          if(state.my_goods[i].name == product.name){
              flag = false;
          }
      }
      if(flag){
          state.my_goods_number +=1;
          product.number=1;
          state.my_goods.push(product);
          state.need +=product.price; 
      }

    },
    add_num(state,good) {
      for(var i = 0;i< state.my_goods_number;i++){
        if(state.my_goods[i].name == good.name){
             state.my_goods[i].number +=1;
        }
      }
      state.need +=good.price;

    },
    sub_num(state,good) {
      for(var i = 0;i< state.my_goods_number;i++){
        if(state.my_goods[i].name == good.name){
            state.my_goods[i].number -=1;
            if(state.my_goods[i].number <= 0)
                state.my_goods_number -=1;
        }   
      }
      state.my_goods = state.my_goods.filter(
          function(item){
              return item.number > 0;
          }
      )
      state.need -=good.price;

    },
    del_good(state,good) {
      state.my_goods = state.my_goods.filter(
        function(item){
            return item.name != good.name;
        }
      )
      state.my_goods_number -=1;
      state.need -= good.number*good.price;
    },
  },
  actions: {

  },
  getters: {
    getCount: state => {
      return state.need; // 获取当前计数值
    },
  },
})